package com.elinkway.infinitemovies.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.AlbumGridViewAdapter;
import com.elinkway.infinitemovies.adapter.ReportPhotoAdapter;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.FeedbackQuestionBean;
import com.elinkway.infinitemovies.bean.ReportSubmitBean;
import com.elinkway.infinitemovies.http.requesttask.SubmitFeedbackQuestionTask;
import com.elinkway.infinitemovies.listener.OnReportListener;
import com.elinkway.infinitemovies.ui.fragment.CopyrightFragment;
import com.elinkway.infinitemovies.utils.BitmapUtils;
import com.elinkway.infinitemovies.utils.FileUtils;
import com.elinkway.infinitemovies.utils.ImageItem;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MyLocationManager;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.le123.ysdq.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FeedbackSubmitActivity extends BaseActionBarActivity implements View.OnClickListener{

    public final static String SUB_QUESTION_LIST = "subQuestionList";
    public final static String AID = "aid";
    public final static String SITE = "site";
    public final static String SCOPE = "scope";
    private ArrayList<FeedbackQuestionBean.Subcategory> subQuestionList;
    private String mAid;
    private String mSite;
    private String mScope;
    private String mSubscope;
    private String mDescription;
    private String mContact;
    private RecyclerView mRecyclerView;
    private Button mSubmit;
    private QuestionItemAdapter mQuestionItemAdapter;
    private RelativeLayout mPopParent;
    private PopupWindow mPop;
    private LinearLayout mLinearPopupWindow;
    private View mPopView;
    private Button mBtCamera;
    private Button mBtFromPicture;
    private Button mCancel;
    private boolean isCheckQuestion = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback_submit);
        initActionBar();
        initView();
        initData();
    }

    @Override
    public void dealWithUmeng() {

    }

    @Override
    public void dealWithVisitUmeng() {

    }


    private void initView() {
        mTitleTv.setText(getString(R.string.feedback));
        mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mQuestionItemAdapter = new QuestionItemAdapter(this, new ItemClickListener() {

            @Override
            public void onItemClick(View view, int position) {
                if (view instanceof LinearLayout) {
                    questionItemSelectState(view, position);
                }

//                else if (view instanceof RelativeLayout) {
//                    if (position == BitmapUtils.selectBitmap.size()) {
//                        if (mPop == null || mLinearPopupWindow == null) {
//                            return;
//                        }
//                        mLinearPopupWindow.startAnimation(AnimationUtils.loadAnimation(FeedbackSubmitActivity.this,
//                                R.anim.activity_translate_in));
//                        mPop.showAtLocation(mRecyclerView, Gravity.BOTTOM, 0, 0);
//                    }
//                }
            }
        });
        mRecyclerView.setAdapter(mQuestionItemAdapter);
        mSubmit = (Button) findViewById(R.id.submit);
        mSubmit.setOnClickListener(this);
//        initPopView();
    }

    private void initPopView() {
        mPopView = LayoutInflater.from(this).inflate(R.layout.item_popupwindows, null);
        mLinearPopupWindow = (LinearLayout) mPopView.findViewById(R.id.ll_popup);
        mPopParent = (RelativeLayout) mPopView.findViewById(R.id.parent);
        mBtCamera = (Button) mPopView.findViewById(R.id.item_popupwindows_camera);
        mBtFromPicture = (Button) mPopView.findViewById(R.id.item_popupwindows_Photo);
        mCancel = (Button) mPopView.findViewById(R.id.item_popupwindows_cancel);
        mPop = new PopupWindow(this);
        mPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setFocusable(true);
        mPop.setOutsideTouchable(true);
        mPop.setContentView(mPopView);
        mPopParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });

        mBtCamera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                photo();
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });
        mBtFromPicture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                BitmapUtils.copyImageItem(BitmapUtils.tempSelectBitmap, BitmapUtils.selectBitmap);
                Intent intent = new Intent(FeedbackSubmitActivity.this, AlbumActivity.class);
                startActivityForResult(intent, CopyrightFragment.GET_PICTURE);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });
        mCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });
    }

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, CopyrightFragment.TAKE_PICTURE);
    }

    private void initData() {
        Intent intent = getIntent();
        subQuestionList = (ArrayList<FeedbackQuestionBean.Subcategory>) intent.getSerializableExtra(SUB_QUESTION_LIST);
        if (mQuestionItemAdapter != null && subQuestionList != null) {
            mQuestionItemAdapter.updateList(subQuestionList);
        }
        mAid = intent.getStringExtra(AID);
        mSite = intent.getStringExtra(SITE);
        mScope = intent.getStringExtra(SCOPE);
    }

    @Override
    public void onClick(View v) {
        submitData();
    }

    public class QuestionItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private static final int TYPE_QUESTION = 0;
        private static final int TYPE_ADVICE = 1;

        private Context mContext;
        private ItemClickListener mItemClickListener;

        private List<FeedbackQuestionBean.Subcategory> mData = new ArrayList<>();

        public QuestionItemAdapter(Context context, ItemClickListener itemClickListener) {
            mContext = context;
            mItemClickListener = itemClickListener;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ADVICE) {
                DesViewHolder tDesViewHolder = new DesViewHolder(mContext, LayoutInflater.from(mContext).inflate(R.layout.feedback_photo_item, parent, false),
                        mItemClickListener);
                return tDesViewHolder;
            }

            View view = LayoutInflater.from(mContext).inflate(R.layout.question_item, parent, false);
            QuestionViewHolder tQuestionViewHolder = new QuestionViewHolder(view, mItemClickListener);
            return tQuestionViewHolder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (position == getItemCount() - 1) {
//                if (holder instanceof DesViewHolder) {
//                    ((DesViewHolder)holder).mPhotoAdapter.notifyDataSetChanged();
//                    ((DesViewHolder)holder).description.setText(mDescription);
//                    ((DesViewHolder)holder).contact.setText(mContact);
//                }
                return;
            }
            FeedbackQuestionBean.Subcategory subQuestionItem = mData.get(position);
            if (subQuestionItem == null) {
                return;
            }
            switch (getItemViewType(position)) {
                case TYPE_QUESTION:
                    if (holder instanceof QuestionViewHolder) {
                        ((QuestionViewHolder)holder).question.setText(mData.get(position).name);
                    }
                    break;
                default:
                    break;

            }
        }

        @Override
        public int getItemViewType(int position) {
            if (position == getItemCount() - 1){
                return TYPE_ADVICE;
            }

            return TYPE_QUESTION;
        }

        @Override
        public int getItemCount() {
            return mData.size() + 1;
        }

        public void updateList(List<FeedbackQuestionBean.Subcategory> data) {
            mData = data;
            notifyDataSetChanged();
        }

        public String getClickItemSubScopeId(int position) {
            if (position < mData.size()) {
                return mData.get(position).id;
            }
            return "";
        }

        public void setOnItemClickListener(ItemClickListener listener){
            this.mItemClickListener = listener;
        }
    }

    private class QuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView question;
        ImageView arrow_right;
        CheckBox selected;
        ItemClickListener mItemClickListener;

        public QuestionViewHolder(View itemView, ItemClickListener itemClickListener) {
            super(itemView);
            question = (TextView) itemView.findViewById(R.id.question);
            arrow_right = (ImageView) itemView.findViewById(R.id.question_arrow_right);
            arrow_right.setVisibility(View.GONE);
            selected = (CheckBox) itemView.findViewById(R.id.question_check);
            selected.setChecked(false);
            selected.setVisibility(View.VISIBLE);
            mItemClickListener = itemClickListener;
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null) {
                mItemClickListener.onItemClick(v, getLayoutPosition());
            }
        }
    }

    private class DesViewHolder extends RecyclerView.ViewHolder implements AdapterView.OnItemClickListener{
        EditText description;
        EditText contact;
//        GridView mGridItemPhotoView;
//        ReportPhotoAdapter mPhotoAdapter;
//        ItemClickListener mItemClickListener;

        public DesViewHolder(final Context context, View itemView, ItemClickListener itemClickListener) {
            super(itemView);
//            mItemClickListener = itemClickListener;
            description = (EditText) itemView.findViewById(R.id.description);
            contact = (EditText) itemView.findViewById(R.id.contact);
//            mGridItemPhotoView = (GridView) itemView.findViewById(R.id.gv_report_grid_photo);
//            mPhotoAdapter = new ReportPhotoAdapter(context, mAid);
//            mGridItemPhotoView.setAdapter(mPhotoAdapter);
//            mGridItemPhotoView.setOnItemClickListener(this);
            contact.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    mContact = s.toString();
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            description.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    mDescription = s.toString();
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            mItemClickListener.onItemClick(view, position);
        }
    }

    private interface ItemClickListener {
        void onItemClick(View view, int position);
    }

    private void changeSubmitButtonState(boolean isEnable) {
        if (isEnable) {
            mSubmit.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_3599f8));
            mSubmit.setEnabled(true);
        } else {
            mSubmit.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_DDDDDD));
            mSubmit.setEnabled(false);
        }
    }

    private void questionItemSelectState(View view, int position) {
        CheckBox currentItemCheckBox = ((CheckBox)view.findViewById(R.id.question_check));
        if (currentItemCheckBox == null) {
            return;
        }

        if (currentItemCheckBox.isChecked()) {
            isCheckQuestion = false;
            currentItemCheckBox.setChecked(false);
        } else {
            for (int i = 0; i < mQuestionItemAdapter.getItemCount(); i++) {
                View itemView = mRecyclerView.getChildAt(i);
                if (itemView == null) {
                    continue;
                }
                CheckBox tView = (CheckBox) mRecyclerView.getChildAt(i).findViewById(R.id.question_check);
                if (tView == null) {
                    continue;
                }
                if (tView.isChecked()) {
                    tView.setChecked(false);
                }
            }
            currentItemCheckBox.setChecked(true);
            mSubscope = mQuestionItemAdapter.getClickItemSubScopeId(position);
            isCheckQuestion = true;
        }
    }

    private void submitData() {
        if (!isCheckQuestion) {
            ToastUtil.showLongToast(this, getString(R.string.no_question));
            return;
        }
        if (StringUtil.isEmpty(mDescription)) {
            ToastUtil.showLongToast(this, getString(R.string.no_detail));
            return;
        }
        if (StringUtil.isEmpty(mContact)) {
            ToastUtil.showLongToast(this, getString(R.string.no_contact));
            return;
        }

        SubmitFeedbackQuestionTask requestTask = new SubmitFeedbackQuestionTask(this, mAid, mSite, SharePreferenceManager.getVaule(this, MyLocationManager.LOCATIONKEY, "CN_1_5_1"),
                mScope, mSubscope, mDescription, mContact);
        requestTask.setListener(new RequestResultListener<ReportSubmitBean>() {
            @Override
            public boolean onRequestFailed() {
                ToastUtil.showLongToast(getApplicationContext(), getString(R.string.feedback_fail));
                return false;
            }

            @Override
            public void onRequestSuccess(int updateId, ReportSubmitBean result) {
                ToastUtil.showLongToast(getApplicationContext(), getString(R.string.feedback_tip));
                finish();
            }

            @Override
            public void onPreRequest() {

            }
        });
        requestTask.start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e(TAG, "onActivityResult " + requestCode + " " + resultCode);
        switch (requestCode) {
            case CopyrightFragment.TAKE_PICTURE:
                if (BitmapUtils.selectBitmap.size() < 9 && resultCode == RESULT_OK) {

                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);

                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    takePhoto.setImagePath(FileUtils.SDPATH + fileName + ".JPEG");
                    takePhoto.setBitFile(new File(takePhoto.getImagePath()));
                    BitmapUtils.selectBitmap.add(takePhoto);
                    mQuestionItemAdapter.notifyItemChanged(mQuestionItemAdapter.getItemCount() - 1);
                }
                break;
            case CopyrightFragment.GET_PICTURE:
                mQuestionItemAdapter.notifyItemChanged(mQuestionItemAdapter.getItemCount() - 1);
                break;

        }
    }

    public static void launchActivity(Context context, String aid, String site, String scope, ArrayList<FeedbackQuestionBean.Subcategory> subQuestionList) {
        Intent intent = new Intent(context, FeedbackSubmitActivity.class);
        intent.putExtra(SUB_QUESTION_LIST, subQuestionList);
        intent.putExtra(AID, aid);
        intent.putExtra(SITE, site);
        intent.putExtra(SCOPE, scope);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapUtils.selectBitmap.clear();
    }
}

